package com.fare.taluo.application.impl;




import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fare.taluo.core.domain.Convert;
import com.fare.taluo.core.domain.analyse.report.upload.ReportUploadInfo;
import com.fare.taluo.vo.core.ReportDownloadQueryVo;
import com.fare.taluo.vo.core.ReportUploadInfoVO;
import com.fare.taluo.application.ReportDownloadApplication;
import com.dayatang.querychannel.service.QueryChannelService;
import com.dayatang.querychannel.support.Page;
import com.opensymphony.oscache.util.StringUtil;

@Transactional
@Scope("singleton")
@Service("reportDownloadApplicationImpl")
public class ReportDownloadApplicationImpl   implements ReportDownloadApplication{
	

	private static final Logger logger = LoggerFactory.getLogger(ReportDownloadApplicationImpl.class);

	@Autowired
	public  QueryChannelService queryChannel1;
	
	/**
	 * @see ReportDownloadApplicationImpl#findByPage(ReportDownloadQueryVo, int, int)
	 * */
	public Page<ReportUploadInfoVO> findByPage(ReportDownloadQueryVo query,int pageNo, int pageSize){
		List<ReportUploadInfoVO> listVo = new ArrayList<ReportUploadInfoVO>();
		StringBuffer hql = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		hql.append(" from ReportUploadInfo where 1=1 ");
		if(query != null){
			if(!StringUtil.isEmpty(query.getName())){
				hql.append(" and name like ? ");
				params.add("%"+query.getName()+"%");
			}
			
			if(query.getYear()>0){
				hql.append(" and report_year=? ");
				params.add(query.getYear());
			}
			if(query.getMonth()>=1 && query.getMonth()<=12){
				hql.append(" and report_month=? ");
				params.add(query.getMonth());
			}
		}
		hql.append(" order by uploadDate desc ");
		
		Page<ReportUploadInfo> page = queryChannel1.queryPagedResultByPageNo(hql.toString(), params.toArray(), pageNo, pageSize);
		if(page.getTotalCount() > 0){
			for(ReportUploadInfo entity : page.getResult()){
				listVo.add(Convert.convertReportUploadInfoVo(entity));
			}
		}
		int start = (pageNo - 1)*pageSize;
		return new Page<ReportUploadInfoVO>(start, page.getTotalCount(), pageSize, listVo);
		
	}

	/**
	 * @see ReportDownloadApplicationImpl#download(String, HttpServletResponse)
	 * */
	public void download(String id, HttpServletResponse response,HttpServletRequest request)throws Exception {

		ReportUploadInfo rui = ReportUploadInfo.get(Long.parseLong(id));
		//文件原名
		String fileName =rui.getName();
		//所在地址
		File file = new File(rui.getPath());
		if(!file.exists()){
			throw new Exception("文件不存在");
		}
		InputStream inStream = null;
		ServletOutputStream out = null;

		try {
			inStream = new FileInputStream(file);
			out = response.getOutputStream();
			response.reset();
			// 设置输出的格式
			response.setContentType("application/pdf;charset=UTF-8");
			if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0){
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
			}else{
				fileName = URLEncoder.encode(fileName, "UTF-8");//其他浏览器
			}
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
			// 循环取出流中的数据
			byte[] b = new byte[1024*256];
			int len;
			while ((len = inStream.read(b)) > 0){
				out.write(b, 0, len);
			}
			out.flush();
		}catch (Exception e) {
			throw new Exception(e);
		}finally{
			try {
				if(out != null){
					out.close(); 
				}
				if(inStream != null){
					inStream.close();
				}
				//response.flushBuffer();
			} catch (Exception e) {
				throw new Exception(e);
			}
		}
		//=================================================================================

	}
	
	/**
	 * @see ReportDownloadApplicationImpl#saveUploadInfo(String, String, String)
	 * */
	public void saveUploadInfo(String fileName,String miaoshu,String operator)throws Exception{
			ReportUploadInfo entity = new ReportUploadInfo();
			entity.setEscribe(miaoshu);
			entity.setOperator(operator);
			entity.setUploadDate(new Date());
			entity.setName(fileName);
			entity.save();
	}

	@Override
	public void saveUploadInfo(String fileName, String miaoshu, String path,
			String operator,int year,int month) throws Exception {
			ReportUploadInfo entity = new ReportUploadInfo();
			entity.setName(fileName);
			entity.setEscribe(miaoshu);
			entity.setOperator(operator);
			entity.setUploadDate(new Date());
			entity.setReport_year(year);
			entity.setReport_month(month);
			entity.setPath(path);
			entity.save();
	}
	
	
	public ReportUploadInfoVO findById(String id) throws Exception{
		ReportUploadInfoVO vo=null;
		String hql=" from ReportUploadInfo where id=? ";
		List<Object> params = new ArrayList<Object>();
		params.add(Long.valueOf(id));
		Page<ReportUploadInfo> page = queryChannel1.queryPagedResultByPageNo(hql, params.toArray(), 1, 1);
		
		if(page.getTotalCount()==1){
			vo=Convert.convertReportUploadInfoVo(page.getResult().get(0));
		}
		return vo;
	}
}
